<!-- components/ExcelUploader.vue -->
<template>
  <div>
    <div class="desc">上传 Excel 文件</div>
    <input
      class="desc"
      type="file"
      @change="handleFileUpload"
      accept=".xls,.xlsx"
    />
    <div v-if="jsonData">
      <div class="desc">解析后的 JSON 数据</div>
      <pre>{{ jsonData[0] }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx";

const emit = defineEmits(["done"]);

const jsonData = ref(null);

watch(
  () => jsonData.value,
  (newVal) => {
    if (newVal) emit("done", newVal);
  }
);

const handleFileUpload = (event) => {
  const file = event.target.files[0];
  const reader = new FileReader();

  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });

    // 读取第一个工作表
    const jsonSheet = XLSX.utils.sheet_to_json(
      workbook.Sheets[workbook.SheetNames[0]]
    );
    jsonData.value = jsonSheet;
  };

  reader.readAsArrayBuffer(file);
};
</script>

<style lang="scss" scoped>
.desc {
  width: 100vw;
  margin: 12 * 2px;
  font-size: 17 * 2px;
  font-weight: 400;
}

pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 5px;
}
</style>
